﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using CardLogistics.Web.Components;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Xml;

namespace CardLogistics.Web
{
    public partial class WebForm1 : BasePage
    {
        protected StringBuilder sbStr = new StringBuilder();
        protected void Page_Load(object sender, EventArgs e)
        {
            //WebUserControl11.DhStr = "1";


            //DataTable dt = CardLogistics.DAL.DbHelperSQL.GetQueryResult("  select * from v_approvalinfo where userid='" + LoggedUser.ID + "' ");
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dt.Rows)
            //    {
            //        sbStr.Append("<li><a href='#'>" + dr["typeName"].ToString() + "---" + dr["ADDDATE"].ToString() + "</a></li>");
            //    }
            //}
            //string a = GetByClient();
           // string a1 = GetResponseData("","http://10.0.8.149:8081/api/logistics/GetCardInfo?bgTime=20160101&endTime=20160101");
            //string aa = WebServiceApp("http://10.0.24.53:8087/api/logistics/", "GetCardInfo?bgTime=20160101&endTime=20160101", "");

        }
 
        public static string HttpGet(string url)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "textml, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }

        }

       
        public string HttpGet2(string url)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "textml, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
        /// <summary>
        /// 根据电话号码获取政企一卡通用户状态
        /// </summary>
        /// <param name="mobStr">手机号</param>
        /// <returns>用户当前状态</returns>
        private string GetUrl()
        {
            //string xmlStr = M10086_03(mobStr);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://10.0.24.20:8087/api/logistics/GetCardInfo?bgTime=20160101&endTime=20160101");
            Encoding encoding = Encoding.GetEncoding("utf-8");
            string postData = "";
            byte[] bs = Encoding.ASCII.GetBytes(postData);//把文本内容转换成二进制数组发送
            string responseData = String.Empty;
            req.Method = "POST";//页面提交方式
            req.ContentType = "application-json";
            req.ContentLength = bs.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd().ToString();//读取返回的消息
                }
            }
            string tmp = responseData;

            return tmp;

            //XmlDocument xmlTmp = new XmlDocument();
            //xmlTmp.LoadXml(responseData);//将返回的结果加载到xml中
            //string root = xmlTmp.ChildNodes[0].ChildNodes[13].InnerXml;//获取SvcCont 标签中显示的内容
            //return root;
        }


        public static string PostData(string url, string data)
        {
            // Convert to bytes
            string UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
            string strReturn = "";

            try
            {
                byte[] obtPostData = Encoding.UTF8.GetBytes(data);
                HttpWebRequest orqRequest = (HttpWebRequest)WebRequest.Create(url);
                orqRequest.Timeout = 3000;

                orqRequest.Method = "POST";
                orqRequest.UserAgent = UserAgent;
                //orqRequest.Referer = LoginRefererUrl;
                orqRequest.ContentType = "application/x-www-form-urlencoded";
                orqRequest.ContentLength = obtPostData.Length;
                orqRequest.AllowAutoRedirect = false;

                // Add post data to request

                Stream stream;
                using (stream = orqRequest.GetRequestStream())
                {
                    stream.Write(obtPostData, 0, obtPostData.Length);
                }

                HttpWebResponse orsResponse = (HttpWebResponse)orqRequest.GetResponse();

                using (Stream responseStream = orsResponse.GetResponseStream())
                {
                    using (StreamReader streamRead = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        strReturn = streamRead.ReadToEnd();
                    }
                }

            }
            catch (Exception e)
            {
                //throw new Exception(e.Message);
            }

            return strReturn;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="method">方法</param>
        /// <param name="param">json参数</param>
        /// <returns></returns>
        public static string WebServiceApp(string url, string method, string param)
        {
            //转换输入参数的编码类型，获取bytep[]数组 
            byte[] byteArray = Encoding.UTF8.GetBytes("json=" + param);
            //初始化新的webRequst
            //1． 创建httpWebRequest对象
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + method));
            //2． 初始化HttpWebRequest对象
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
            //3． 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊，它并没有提供一个属性给用户存取，需要写入HttpWebRequest对象提供的一个stream里面。)
            Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();
            //4． 读取服务器的返回信息
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string phpend = php.ReadToEnd();
            return phpend;

        }

        #region 将json转换为DataTable
        /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns></returns>
        private DataTable JsonToDataTable(string strJson)
        {
            //转换json格式
            strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));
            //获取数据   
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');
                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');
                        if (strCell[0].Substring(0, 1) == "\"")
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a - 2);
                        }
                        else
                        {
                            dc.ColumnName = strCell[0];
                        }
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }
                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;
        }
        #endregion
    }
}